package com.self.smallma.myblogweb.service.impl;

import com.self.smallma.myblogweb.vo.LoginVo;
import com.self.smallma.myblogweb.vo.RegisterVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.self.smallma.myblogweb.common.utils.PageUtils;
import com.self.smallma.myblogweb.common.utils.Query;

import com.self.smallma.myblogweb.dao.UserDao;
import com.self.smallma.myblogweb.entity.UserEntity;
import com.self.smallma.myblogweb.service.UserService;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotEmpty;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    UserDao userDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }
    //注册
    @Override
    public int register(RegisterVo registerVo) {
        //校验验证码
        String code = registerVo.getCode();
        String redisCode = redisTemplate.opsForValue().get("sms:code" + registerVo.getPhone());
        if (!StringUtils.isEmpty(redisCode)){
           if (code.equals( redisCode.split("_")[0])){
               //删除验证码
               redisTemplate.delete("sms:code" + registerVo.getPhone());
               //说明验证码正确
                //判断是否是重复用户
               List<UserEntity> list = this.list(new QueryWrapper<UserEntity>().eq("username", registerVo.getUsername())
                       .or().eq("email", registerVo.getEmail()));
               if (list.size()==0){
                   //如果没有该用户
                   UserEntity userEntity = new UserEntity();
//               userEntity.setEmail(registerVo.getEmail());
//               userEntity.setPhone(registerVo.getPhone());
                   BeanUtils.copyProperties(registerVo,userEntity);
                   // 用户头像随机给
                   userEntity.setAvatar(getRandomImg());
                   userEntity.setCreateTime(new Date());
                   userEntity.setUpdateTime(new Date());
                   userEntity.setType(0);
                   //进行md5盐值加密
                   BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
                   String encode = passwordEncoder.encode(registerVo.getPassword());
                   userEntity.setPassword(encode);
                   int i = this.baseMapper.insert(userEntity);
                   return i;
               }else {
                   return 0;
               }
           }else {
               return 0;
           }
        }else {
            //说明验证码过期
            return 0;
        }

    }
    /**
     * 放在CDN上的随机头像
     */
    private static final String [] headImg = {
            "https://xd-video-pc-img.oss-cn-beijing.aliyuncs.com/xdclass_pro/default/head_img/12.jpeg",
            "https://xd-video-pc-img.oss-cn-beijing.aliyuncs.com/xdclass_pro/default/head_img/11.jpeg",
            "https://xd-video-pc-img.oss-cn-beijing.aliyuncs.com/xdclass_pro/default/head_img/13.jpeg",
            "https://xd-video-pc-img.oss-cn-beijing.aliyuncs.com/xdclass_pro/default/head_img/14.jpeg",
            "https://xd-video-pc-img.oss-cn-beijing.aliyuncs.com/xdclass_pro/default/head_img/15.jpeg"
    };

    private String getRandomImg(){
        Random random = new Random();
        int i = random.nextInt(headImg.length);
        return headImg[i];
    }

    //登录
    @Override
    public UserEntity login(LoginVo loginVo) {
        String loginacct = loginVo.getLoginacct();
        String password = loginVo.getPassword();

        //查询数据库
        UserEntity userEntity = this.baseMapper.selectOne(new QueryWrapper<UserEntity>()
                .eq("username", loginacct)
                .or().eq("email", loginacct)
        );
        if (userEntity==null){
            //登录失败
            return null;
        }else {
            //数据库中的值
            String pwd = userEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //密码匹配
            boolean matches = passwordEncoder.matches(password, pwd);
            if (matches){
                //匹配成功
                return userEntity;
            }else {
                return null;
            }
        }
    }



}